package com.kukudb.captcharepeater.utils;

import com.kukudb.captcharepeater.pojo.Promoters;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JWTUtils {

    public static final String SECRET = "kukudb-kukudb-kukudb-kukudb-kukudb"; // 至少32位
    private static final SecretKey KEY = Keys.hmacShaKeyFor(SECRET.getBytes(StandardCharsets.UTF_8));
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 7; // 7天

    public static String createToken(Promoters promoters) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", promoters.getId());

        return Jwts.builder()
                .claims(claims)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(KEY)
                .compact();
    }

    public static Map<String, Object> checkToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .verifyWith(KEY)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();

            log.info("token 验证成功");
            Map<String, Object> result = new HashMap<>();
            result.put("userId", claims.get("userId"));
            return result;
        } catch (Exception e) {
            log.error("token 验证失败", e);
            return null;
        }
    }

    public static Integer getSessionUserId(HttpSession session) {
        try {
            Object tokenObj = session.getAttribute("token");
            if (tokenObj == null) {
                throw new IllegalArgumentException("token不存在，请重新登录");
            }

            Map<String, Object> tokenData = checkToken(tokenObj.toString());
            if (tokenData == null) {
                throw new IllegalArgumentException("token验证失败，请重新登录");
            }

            return (Integer) tokenData.get("userId");
        } catch (Exception e) {
            log.error("获取用户ID失败", e);
            throw new IllegalArgumentException("获取失败，未登录");
        }
    }

    public static void main(String[] args) {
        Promoters promoters = new Promoters();
        promoters.setId(1);
        promoters.setUsername("admin");
        promoters.setPassword("123456");
        promoters.setEmail("admin@qq.com");

        String token = createToken(promoters);
        System.out.println("生成的Token: " + token);

        Map<String, Object> map = checkToken(token);
        System.out.println("解析结果: " + map);
    }
}